<?php
declare(strict_types=1);

namespace App\Admin\Actions\Message;

use App\Constant\CacheKey;
use App\Library\RedisClient;
use App\Models\Admin\Message\TemplateConfig;
use App\Models\Admin\Message\TemplateHistory;
use App\Models\Admin\User\User;
use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class SendMiNiTemplateAction extends RowAction
{
    public $name = "发送消息";

    public function handle(Model $model, Request $request): Response
    {
        $requestParams = $request->all();
        // 如果是指定用户的uid
        if (!empty($requestParams["send_people"])) {
            $userUidArray = explode(",", str_replace("，", ",", $requestParams["send_people"]));
        } else {
            $userUidObject = TemplateHistory::query()
                ->where("template_id", "=", $requestParams["template_id"])
                ->where([
                    ["is_used", "=", 2],
                    ["send_sate", "=", 3]
                ])
                ->get(["user_uid"])
                ->toArray();
            $userUidArray = [];
            foreach ($userUidObject as $value) {
                $userUidArray[] = $value->user_uid;
            }
        }
        // 根据用户uid查询对应的openid
        $userOpenidObject = User::query()->where("uid", $userUidArray)->get(["openid"])->toArray();
        $userOpenidArray = [];
        foreach ($userOpenidObject as $value) {
            $userOpenidArray[] = $value->openid;
        }
        // 组装数据
        $values = TemplateConfig::query()->where("id", "=", $requestParams["id"])
            ->first(["values"])
            ->toArray();
        $data = [];
        foreach ($values["values"] as $key => $value) {
            $data[$value["key"]] = [
                "value" => $requestParams["key" . $key],
            ];
        }
        $redis = RedisClient::client();
        $result = false;
        foreach ($userOpenidArray as $value) {
            $result = $redis->lPush(CacheKey::MiNITemplateQueue, json_encode($data = [
                'template_id' => $requestParams["template_id"],
                'touser' => $value,
                'page' => $requestParams["navigator"],
                'data' => $data,
            ], JSON_UNESCAPED_UNICODE));
        }
        if ($result) {
            return $this->response()->success("成功添加{$result}条数据到任务队列中")->refresh();
        }
        return $this->response()->error("添加失败")->refresh();
    }

    public function form()
    {
        $id = $this->getKey();
        $bean = TemplateConfig::query()->where("id", "=", $id)
            ->first(["template_id", "navigator", "values"])
            ->toArray();
        $this->hidden("id", "配置编号")->default($id)->readonly();
        $this->text("navigator", "跳转路径")->required()->default($bean["navigator"])->help("不填写则表示不进行跳转");
        $this->text("template_id", "订阅模板")->required()->default($bean["template_id"])->readonly();
        $this->textarea("send_people", "发送人")
            ->help("如果指定发送人，复制用户的编号，并用','隔开。不填写表示发送所有人。");
        foreach ($bean["values"] as $key => $value) {
            $type = $value["type"] ?? "";
            $this->text("key" . $key, "(通知事项)" . "-|" . $value["desc"])
                ->default($value["value"])
                ->help(empty($type) ? "" : CacheKey::MiNiWeChatTemplateConfig[$type])
                ->required();
        }
    }
}
